import { useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components/ui/tabs";
import { DatabaseCard } from "./components/DatabaseCard";
import { CreateDatabaseDialog } from "./components/CreateDatabaseDialog";
import { SlowQueryMonitor } from "./components/SlowQueryMonitor";
import { DatabaseSpaceMonitor } from "./components/DatabaseSpaceMonitor";
import { PerformanceMonitor } from "./components/PerformanceMonitor";
import { LanguageSelector } from "./components/LanguageSelector";
import { LoginForm } from "./components/LoginForm";
import { UserMenu } from "./components/UserMenu";
import { DataSourceSwitcher } from "./components/DataSourceSwitcher";
import { Card, CardContent, CardHeader, CardTitle } from "./components/ui/card";
import { Badge } from "./components/ui/badge";
import { 
  Database, 
  BarChart3, 
  AlertTriangle, 
  HardDrive,
  Activity,
  TrendingUp,
  Users,
  Server
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { I18nProvider, useI18n } from "./lib/i18n/context";
import { AuthProvider, useAuth } from "./lib/auth/context";
import { DataSourceProvider, useDataSource } from "./lib/data/context";

function DatabaseManagementApp() {
  const { t } = useI18n();
  const { isAuthenticated, isLoading } = useAuth();
  const { 
    databases, 
    createDatabase, 
    startDatabase, 
    stopDatabase, 
    deleteDatabase 
  } = useDataSource();
  const [activeTab, setActiveTab] = useState('overview');

  const handleCreateDatabase = async (newDatabase: any) => {
    try {
      const created = await createDatabase(newDatabase);
      toast.success(`${t.instances.title} "${created.name}" ${t.messages.databaseCreated}`);
      
      // For mock data, show additional success message after status change
      setTimeout(() => {
        toast.success(`${t.instances.title} "${created.name}" ${t.messages.databaseRunning}`);
      }, 3000);
    } catch (error) {
      console.error('Failed to create database:', error);
    }
  };

  const handleStartDatabase = async (id: string) => {
    try {
      await startDatabase(id);
      toast.success(t.messages.databaseStarted);
    } catch (error) {
      console.error('Failed to start database:', error);
    }
  };

  const handleStopDatabase = async (id: string) => {
    try {
      await stopDatabase(id);
      toast.success(t.messages.databaseStopped);
    } catch (error) {
      console.error('Failed to stop database:', error);
    }
  };

  const handleDeleteDatabase = async (id: string) => {
    try {
      const dbName = databases.find(db => db.id === id)?.name;
      await deleteDatabase(id);
      toast.success(`${t.instances.title} "${dbName}" ${t.messages.databaseDeleted}`);
    } catch (error) {
      console.error('Failed to delete database:', error);
    }
  };

  const handleViewDetails = (id: string) => {
    const database = databases.find(db => db.id === id);
    toast.info(`${t.messages.viewingDetails} ${database?.name}`);
  };

  const runningDatabases = databases.filter(db => db.status === 'running').length;
  const totalConnections = databases.reduce((sum, db) => sum + db.connections, 0);
  const avgCpu = databases.length > 0 ? databases.reduce((sum, db) => sum + db.cpu, 0) / databases.length : 0;
  const totalStorage = databases.reduce((sum, db) => sum + db.storage, 0);

  // Show loading screen while checking authentication
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-center">
          <Database className="h-12 w-12 text-blue-600 mx-auto mb-4 animate-pulse" />
          <p className="text-muted-foreground">{t.common.loading}</p>
        </div>
      </div>
    );
  }

  // Show login form if not authenticated
  if (!isAuthenticated) {
    return <LoginForm />;
  }

  return (
    <div className="min-h-screen bg-background p-4">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center space-x-3">
              <Database className="h-8 w-8 text-blue-600" />
              <h1 className="text-3xl font-bold">{t.header.title}</h1>
            </div>
            <div className="flex items-center space-x-4">
              <DataSourceSwitcher />
              <LanguageSelector />
              <UserMenu />
            </div>
          </div>
          <p className="text-muted-foreground">
            {t.header.subtitle}
          </p>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
          <Card>
            <CardContent className="flex items-center p-6">
              <div className="flex items-center space-x-4">
                <Server className="h-8 w-8 text-blue-600" />
                <div>
                  <p className="text-sm text-muted-foreground">{t.stats.runningInstances}</p>
                  <p className="text-2xl font-bold">{runningDatabases}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center p-6">
              <div className="flex items-center space-x-4">
                <Users className="h-8 w-8 text-green-600" />
                <div>
                  <p className="text-sm text-muted-foreground">{t.stats.totalConnections}</p>
                  <p className="text-2xl font-bold">{totalConnections}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center p-6">
              <div className="flex items-center space-x-4">
                <Activity className="h-8 w-8 text-orange-600" />
                <div>
                  <p className="text-sm text-muted-foreground">{t.stats.avgCpuUsage}</p>
                  <p className="text-2xl font-bold">{avgCpu.toFixed(1)}%</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center p-6">
              <div className="flex items-center space-x-4">
                <HardDrive className="h-8 w-8 text-purple-600" />
                <div>
                  <p className="text-sm text-muted-foreground">{t.stats.totalStorage}</p>
                  <p className="text-2xl font-bold">{totalStorage} GB</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Main Content */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="overview" className="flex items-center space-x-2">
              <Database className="h-4 w-4" />
              <span>{t.navigation.instances}</span>
            </TabsTrigger>
            <TabsTrigger value="performance" className="flex items-center space-x-2">
              <BarChart3 className="h-4 w-4" />
              <span>{t.navigation.performance}</span>
            </TabsTrigger>
            <TabsTrigger value="slow-queries" className="flex items-center space-x-2">
              <AlertTriangle className="h-4 w-4" />
              <span>{t.navigation.slowQueries}</span>
            </TabsTrigger>
            <TabsTrigger value="storage" className="flex items-center space-x-2">
              <HardDrive className="h-4 w-4" />
              <span>{t.navigation.storage}</span>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="mt-6">
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold">{t.instances.title}</h2>
                <CreateDatabaseDialog onCreateDatabase={handleCreateDatabase} />
              </div>
              
              <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                {databases.map(database => (
                  <DatabaseCard
                    key={database.id}
                    database={database}
                    onStart={handleStartDatabase}
                    onStop={handleStopDatabase}
                    onDelete={handleDeleteDatabase}
                    onViewDetails={handleViewDetails}
                  />
                ))}
              </div>

              {databases.length === 0 && (
                <Card className="text-center py-12">
                  <CardContent>
                    <Database className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                    <h3 className="text-lg font-medium mb-2">{t.instances.noInstances}</h3>
                    <p className="text-muted-foreground mb-4">
                      {t.instances.getStarted}
                    </p>
                    <CreateDatabaseDialog onCreateDatabase={handleCreateDatabase} />
                  </CardContent>
                </Card>
              )}
            </div>
          </TabsContent>

          <TabsContent value="performance" className="mt-6">
            <PerformanceMonitor databases={databases} />
          </TabsContent>

          <TabsContent value="slow-queries" className="mt-6">
            <SlowQueryMonitor />
          </TabsContent>

          <TabsContent value="storage" className="mt-6">
            <DatabaseSpaceMonitor />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}

export default function App() {
  return (
    <I18nProvider>
      <AuthProvider>
        <DataSourceProvider>
          <DatabaseManagementApp />
        </DataSourceProvider>
      </AuthProvider>
    </I18nProvider>
  );
}